// import Taro from '@tarojs/taro';
import { cartList, initOrder } from '../../utils/api';

export default {
  namespace: 'cart',
  state: {
    list: [],
    pagination: []
  },

  effects: {
    * getList({ payload }, { call, put }) {
      const result = yield call(cartList, {
        ...payload
      })
      let list = result.list;
      for(let i = 0; i < list.length; i++){
        list[i] = { ...list[i], ...{selected:0} };
        for(let j = 0; j < list[i].goods.length; j++){
          list[i].goods[j] = { ...list[i].goods[j], ...{selected:0} };
        }
      }
      yield put({
        type: 'updateState',
        payload: {
          list: list,
          pagination: result.pagination
        }
      })
    },

    * addCart({ payload }, { _, put }) {
      yield put({
        type: 'updateCartList',
        payload
      })
    },
    * cartSelect({ payload }, { _, put }) {
      yield put({
        type: 'updateCartSelect',
        payload
      })
    },

    * cartSelectStore({ payload }, { _, put }) {
      yield put({
        type: 'updateCartSelectStore',
        payload
      })
    },

    * cartSelectAll({ payload }, { _, put }) {
      yield put({
        type: 'updateCartSelectAll',
        payload
      })
    },

    * settlement({ payload }, { call, put }) {
      const result = yield call(initOrder, {
        ...payload
      })
    }
  },

  reducers: {
    updateState(state, { payload: list, pagination }) {
      return { ...state, ...JSON.parse(JSON.stringify(list)), ...pagination }
    },

    updateCartSelectAll(state, {payload}){
      return { ...state, ...JSON.parse(JSON.stringify(payload)) }
    },

    updateCartSelectStore(state, {payload}){
      let list = state.list;
      for (let i = 0; i < list.length; i++) {
        if (payload.store_id === list[i].store_id) {
          list[i] = { ...payload }
        }
      }
      return { ...state, ...JSON.parse(JSON.stringify(list)) }
    },

    updateCartSelect(state, {payload}){
      let list = state.list;
      for (let i = 0; i < list.length; i++) {
        if (payload.store_id === list[i].store_id) {
          for (let j = 0; j < list[i].goods.length; j++) {
            if (payload.id === list[i].goods[j].id) {
              list[i].goods[j] = { ...payload }
            }
          }
        }
      }
      return { ...state, ...JSON.parse(JSON.stringify(list)) }
    },

    updateCartList(state, {payload}) {
      let list = state.list;
      for (let i = 0; i < list.length; i++) {
        if (payload.store_id === list[i].store_id) {
          for (let j = 0; j < list[i].goods.length; j++) {
            if (payload.id === list[i].goods[j].id) {
              list[i].goods[j] = { ...payload }
            }
          }
        }
      }
      return { ...state, ...JSON.parse(JSON.stringify(list)) }
    }
  }
}
